package Service

import (
	"fmt"
	"github.com/gorilla/websocket"
	"reflect"
	"server/Dao"
	"server/Database"
	"strconv"
	"strings"
)

type ExcelResponse struct {
	Data  interface{} `json:"data"`
	Error interface{} `json:"error"`
}

type ExcelCommand struct {
	Command string      `json:"command"`
	Params  interface{} `json:"params"`
}

type ExcelCount struct {
	Count int `json:"count" db:"count"`
}

type ExcelCommandHandler func(ws *websocket.Conn, command ExcelCommand)

var excelCommandHandlerChain = make(map[string]ExcelCommandHandler)

func ExcelCommandProcess(ws *websocket.Conn, command ExcelCommand) {
	if excelCommandHandlerChain[command.Command] != nil {
		excelCommandHandlerChain[command.Command](ws, command)
	} else {
		errorMsg := "命令不存在"
		_ = ws.WriteJSON(ExcelResponse{Data: nil, Error: &errorMsg})
	}
}

func RegisterExcelCommandHandler(command string, handler ExcelCommandHandler) {
	excelCommandHandlerChain[command] = handler
}

func SetupExcelCommandHandler() {
	RegisterExcelCommandHandler("getExcelData", getExcelData)
	RegisterExcelCommandHandler("getExcelList", selectExcelList)
}

func getExcelData(ws *websocket.Conn, command ExcelCommand) {
	_ = ws.WriteJSON(ExcelResponse{Data: "Command: getExcelData => Response"})
}

func selectExcelList(ws *websocket.Conn, command ExcelCommand) {
	var excelList []Dao.ExcelDao
	err := Database.MysqlDB.Select(&excelList, "SELECT id,name FROM excel")
	if err != nil {
		_ = ws.WriteJSON(ExcelResponse{Error: err.Error()})
	} else {
		_ = ws.WriteJSON(ExcelResponse{Data: excelList})
		getSheet(ws, command)
	}
}

func getSheet(ws *websocket.Conn, command ExcelCommand) {
	var sheet Dao.ExcelSheet
	var count = 0
	var excelId string
	if reflect.ValueOf(command.Params).IsValid() && strings.HasPrefix(reflect.ValueOf(command.Params).Type().String(), "map") {
		func() {
			for _, key := range reflect.ValueOf(command.Params).MapKeys() {
				if key.String() == "excelId" {
					defer func() {
						err := recover()
						if err != nil {
							fmt.Println(reflect.ValueOf(command.Params).MapIndex(key).Elem().Type().String())
							switch reflect.ValueOf(command.Params).MapIndex(key).Elem().Type().String() {
							case "float64":
								excelId = strconv.FormatFloat(reflect.ValueOf(command.Params).MapIndex(key).Interface().(float64), 'f', -1, 64)
								break
							}
						}
					}()
					excelId = reflect.ValueOf(command.Params).MapIndex(key).Interface().(string)
				}
			}
		}()

		if excelId == "" {
			_ = ws.WriteJSON(ExcelResponse{Error: "excelId 不能为空"})
			return
		}

		err := Database.MysqlDB.Get(&count, "SELECT COUNT(excelId) FROM sheet")
		if count == 0 {
			_ = ws.WriteJSON(ExcelResponse{Data: make(map[string]interface{})})
			return
		}

		err = Database.MysqlDB.Get(&sheet, "SELECT excelId, `index`, name, color, status, `order`, hide, row, `column`, defaultRowHeight, defaultColWidth, scrollLeft, scrollTop, isPivotTable, zoomRatio, showGridLines FROM sheet WHERE `excelId` = ?", excelId)
		fmt.Println(sheet)
		if err != nil {
			_ = ws.WriteJSON(ExcelResponse{Error: err.Error()})
		} else {
			_ = ws.WriteJSON(ExcelResponse{Data: sheet})
		}
	}
}
